package com.example.pushapplication.live.channel;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaCodec;
import android.media.MediaRecorder;

import com.example.pushapplication.live.LivePusher;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AudioChannel {
    private int channels = 2;
    private boolean isLiving;
    private  ExecutorService service;
    private  AudioRecord audioRecord;
    private LivePusher livePusher;
    private int inputSamples;
    public AudioChannel(LivePusher livePusher){
        this.livePusher = livePusher;
        int channelConfig;

        if (channels == 2) {
            channelConfig = AudioFormat.CHANNEL_IN_STEREO;
        } else {
            channelConfig = AudioFormat.CHANNEL_IN_MONO;
        }
        //先被调用，初始化编码
        livePusher.native_setAudioEncInfo(44100, channels);
        //因为是16bt
        inputSamples =  livePusher.getInputSamples() * 2;
        service = Executors.newSingleThreadExecutor();
        //最小需要的缓冲区
        int minBufferSize = AudioRecord.getMinBufferSize(44100, channelConfig,
                AudioFormat.ENCODING_PCM_16BIT) * 2;
        //1、麦克风 2、采样率 3、声道数 4、采样位
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                44100,channelConfig,
                AudioFormat.ENCODING_PCM_16BIT,minBufferSize);
    }
    public void startLive(){
        isLiving = true;
        service.submit(new AudioTeask());

    }
    public void stopLive(){
        isLiving = false;
    }

    public class AudioTeask implements Runnable{

        @Override
        public void run() {
            //开始录音
            audioRecord.startRecording();
            byte[] bytes = new byte[inputSamples];

            while (isLiving){
                //读数据
                int len = audioRecord.read(bytes, 0, bytes.length);
                if (len >0 ){
                    //送去编码
                    livePusher.native_pushAudio(bytes);
                }

            }

            audioRecord.stop();
        }
    }
}
